//
//  ViewController.m
//  TestSemaphore
//
//  Created by yidao171010 on 2020/6/5.
//  Copyright © 2020 yidao171010. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    [self zusai2];
//    [self semaphoreSync2];
    [self serialTest4];
}


#pragma mark - semaphore
- (void)semaphoreSync {
    
    NSLog(@"currentThread---%@",[NSThread currentThread]);  // 打印当前线程
    NSLog(@"semaphore---begin");
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    
    __block int number = 0;
    dispatch_async(queue, ^{
        // 追加任务1
        [NSThread sleepForTimeInterval:2];              // 模拟耗时操作
        NSLog(@"1---%@",[NSThread currentThread]);      // 打印当前线程
        
        number = 100;
        
        dispatch_semaphore_signal(semaphore);
    });
    
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    NSLog(@"semaphore---end,number = %d",number);
}

-(void)semaphoreSync2{//可以看出，如果设置信号量为1，就等同于同步执行的效果
    //crate的value表示，最多几个资源可访问
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);//2,3
    dispatch_queue_t quene = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
     
    //任务1
    dispatch_async(quene, ^{
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        NSLog(@"run task 1");
        sleep(1);
        NSLog(@"complete task 1");
        dispatch_semaphore_signal(semaphore);
    });
    //任务2
    dispatch_async(quene, ^{
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        NSLog(@"run task 2");
        sleep(1);
        NSLog(@"complete task 2");
        dispatch_semaphore_signal(semaphore);
    });
    //任务3
    dispatch_async(quene, ^{
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        NSLog(@"run task 3");
        sleep(1);
        NSLog(@"complete task 3");
        dispatch_semaphore_signal(semaphore);
    });
}

-(void)semaphoreSync3{//也有一些用法是设置信号量为0的，进入任务的时候signal，离开任务的时候wait。
    //crate的value表示，最多几个资源可访问
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);//2,3
    dispatch_queue_t quene = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
     
    //任务1
    dispatch_async(quene, ^{
        dispatch_semaphore_signal(semaphore);
        NSLog(@"run task 1");
        sleep(1);
        NSLog(@"complete task 1");
        
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    });
    //任务2
    dispatch_async(quene, ^{
        dispatch_semaphore_signal(semaphore);
       
        NSLog(@"run task 2");
        sleep(1);
        NSLog(@"complete task 2");
         dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        
    });
    //任务3
    dispatch_async(quene, ^{
        dispatch_semaphore_signal(semaphore);
        
        NSLog(@"run task 3");
        sleep(1);
        NSLog(@"complete task 3");
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    });
}


#pragma mark - dispatch_group_enter
/**
 dispatch_group_enter :通知 group,下个任务要放入 group 中执行了
 dispatch_group_leave: 通知 group,任务成功完成,要移除,与 enter成对出现
 dispatch_group_wait: 在任务组完成时调用，或者任务组超时是调用（完成指的是enter和leave次数一样多）
 dispatch_group_notify: 只要任务全部完成了,就会在最后调用

 我们就可以使用dispatch_group_enter了,在执行了多段之后再在 notify 中执行另一个,类似于栅栏的效果.但是如果是网络请求,需要达到网络请求嵌套的效果,A网络请求完之后再请求 B,需要添加dispatch_group_wait,让线程等待 A 执行完成之后再执行 B.

 作者：闻人歌
 链接：https://www.jianshu.com/p/71fbc0415b5d
 */

// A 请求数据
- (void)loadADataFinished:(void(^)(BOOL success))finished{}
// B 请求数据
- (void)loadBDataFinished:(void(^)(BOOL success))finished{}
// C 请求数据
- (void)loadCDataFinished:(void(^)(BOOL success))finished{}

// 请求是否全部完成
- (void)finishedDataFinished:(void(^)(BOOL success))finished{
      dispatch_group_t group = dispatch_group_create();
      dispatch_group_enter(group);
      [self loadADataFinished:^(BOOL success){
        if (success){
          dispatch_group_leave(group);
        }else{
          finished(NO);
        }
      }];
      dispatch_group_enter(group);
      [self loadBDataFinished:^(BOOL success){
        if (success){
          dispatch_group_leave(group);
        }else{
          finished(NO);
        }
      }];

     dispatch_group_wait(group, DISPATCH_TIME_FOREVER);// A,B同时执行, 执行完才会执行下面的 C
     dispatch_group_enter(group);
     [self loadCDataFinished:^(BOOL success){
        if (success){
          dispatch_group_leave(group);
        }else{
          finished(NO);
        }
      }];
     
      //  group 中的任务都成功完成后,才会返回 YES
      dispatch_group_notify(group, dispatch_get_main_queue(), ^{
            finished(YES);
       });
}

/**
 在我们的项目中,在一个 VC 中会有多个网络请求A,B.现在要实现的是:A 请求数据成功之后,再执行 B 的网络请求.这时候因为网络请求是异步的,所以我们要达到效果,需要在子线程中加入信号量dispatch_semaphore_t,在网络请求内部标记信号量,请求完成之后将信号量清为 0.
 */
- (void)finishedDataFinished2:(void(^)(BOOL success))finished{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{

            dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
             [self loadADataFinished:^(BOOL success){
                if (success){
                  }else{
                     finished(NO);
                 }
                  dispatch_semaphore_signal(semaphore);
             }];
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); // A请求完成之后,请求 B
             [self loadBDataFinished:^(BOOL success){
                if (success){
                  }else{
                     finished(NO);
                 }
                  dispatch_semaphore_signal(semaphore);
             }];
    });
}

#pragma mark - group的两种实现方式
- (void)requestOneWithSuccessBlock:(void(^)(void))block{}
- (void)requestTwoWithSuccessBlock:(void(^)(void))block{}

-(void)semaphoreSync4 {//semaphore方式达到group目的
 dispatch_group_t group = dispatch_group_create();
    
    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_semaphore_t sema = dispatch_semaphore_create(0);
        [self requestOneWithSuccessBlock:^{
            dispatch_semaphore_signal(sema);
        }];
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    });
    
    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_semaphore_t sema = dispatch_semaphore_create(0);
        [self requestTwoWithSuccessBlock:^{
            dispatch_semaphore_signal(sema);
        }];
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    });
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        NSLog(@"全部搞完了");
    });
}

-(void)concurrentByGroup {//dispatch_group_enter方式
    
    dispatch_group_t group = dispatch_group_create();
    
    dispatch_group_enter(group);
    [self requestOneWithSuccessBlock:^{
        dispatch_group_leave(group);
    }];
    
    dispatch_group_enter(group);
    [self requestTwoWithSuccessBlock:^{
        dispatch_group_leave(group);
    }];
    
  // 1 2  都完成 才会执行
    dispatch_group_notify(group, dispatch_get_global_queue(0, 0), ^{
        NSLog(@"all request  done!");
    });
}

/**
 循环请求情况 顺序请求/同时请求
 https://www.jianshu.com/p/92eed31b7421
 */
#pragma mark- 模拟循环网络请求 同时进行 统一回调 (GCD + 信号量方式)
- (void)concurrentTest1 {
    dispatch_group_t group = dispatch_group_create();
    for (int i = 0 ; i < 5; i++) {
        dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            dispatch_semaphore_t sema = dispatch_semaphore_create(0);
             // 模拟请求 ↓
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                sleep(3);
                NSLog(@"任务%d完成",i);
                 dispatch_semaphore_signal(sema);
            });
             // 模拟请求 上
            dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
        });
    }
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        NSLog(@"全部搞完了");
    });
}
//00:21:38.413337+0800 mmmm[4595:182516] 任务1完成
//00:21:38.413337+0800 mmmm[4595:182518] 任务3完成
//00:21:38.413358+0800 mmmm[4595:182517] 任务2完成
//00:21:38.413358+0800 mmmm[4595:182515] 任务0完成
//00:21:38.413447+0800 mmmm[4595:182519] 任务4完成
//00:21:38.413843+0800 mmmm[4595:182428] 全部搞完了

#pragma mark -模拟循环网络请求 同时进行 统一回调 (GCD + group enter/leave 方式)
- (void)concurrentTest2 {
    dispatch_group_t group = dispatch_group_create();
    for (int i = 0 ; i < 5; i++) {
        dispatch_group_enter(group);
          // 模拟请求 ↓
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            sleep(3);
            NSLog(@"任务%d完成",i);
            dispatch_group_leave(group);
        });
          // 模拟请求 ↑
    }
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        NSLog(@"全部搞完了");
    });
}
//2019-04-12 00:26:38.607040+0800 mmmm[4641:184613] 任务0完成
//2019-04-12 00:26:38.607043+0800 mmmm[4641:184612] 任务2完成
//2019-04-12 00:26:38.607059+0800 mmmm[4641:184611] 任务3完成
//2019-04-12 00:26:38.607067+0800 mmmm[4641:184610] 任务1完成
//2019-04-12 00:26:38.607088+0800 mmmm[4641:184625] 任务4完成
//2019-04-12 00:26:38.607353+0800 mmmm[4641:184559] 全部搞完了

#pragma mark -模拟循环网络请求 顺序进行 (GCD + 信号量方式)
- (void)serialTest1 {
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        for (int i = 0 ; i < 5; i++) {
            NSLog(@"开始%d",i);
            // 模拟请求 ↓
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                sleep(3);
                NSLog(@"任务%d完成",i);
                dispatch_semaphore_signal(sema);
            });
            // 模拟请求 上
           dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
        }
        
       NSLog(@"全部搞完了");
    });
}
//2019-04-12 01:31:45.291818+0800 mmmm[5417:215007] 开始0
//2019-04-12 01:31:48.297299+0800 mmmm[5417:215008] 任务0完成
//2019-04-12 01:31:48.297746+0800 mmmm[5417:215007] 开始1
//2019-04-12 01:31:51.298592+0800 mmmm[5417:215008] 任务1完成
//2019-04-12 01:31:51.298841+0800 mmmm[5417:215007] 开始2
//2019-04-12 01:31:54.300477+0800 mmmm[5417:215008] 任务2完成
//2019-04-12 01:31:54.300908+0800 mmmm[5417:215007] 开始3
//2019-04-12 01:31:57.305197+0800 mmmm[5417:215008] 任务3完成
//2019-04-12 01:31:57.305623+0800 mmmm[5417:215007] 开始4
//2019-04-12 01:32:00.311062+0800 mmmm[5417:215008] 任务4完成
//2019-04-12 01:32:00.311407+0800 mmmm[5417:215007] 全部搞完了


#pragma mark -模拟循环网络请求 顺序进行 (GCD + group enter/leave 方式)
- (void)serialTest2 {
    dispatch_group_t group = dispatch_group_create();
    for (int i = 0 ; i < 5; i++) {
        dispatch_group_enter(group);
        // 模拟请求 ↓
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            sleep(6 - i);
            NSLog(@"任务%d完成",i);
            dispatch_group_leave(group);
        });
        // 模拟请求 ↑
        dispatch_group_wait(group, DISPATCH_TIME_FOREVER); // 顺序执行与同步执行的不同点
    }
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        NSLog(@"全部搞完了");
    });
}
//2019-04-12 00:33:46.020376+0800 mmmm[4748:188409] 任务0完成
//2019-04-12 00:33:51.021098+0800 mmmm[4748:188409] 任务1完成
//2019-04-12 00:33:55.022758+0800 mmmm[4748:188409] 任务2完成
//2019-04-12 00:33:58.023783+0800 mmmm[4748:188409] 任务3完成
//2019-04-12 00:34:00.027929+0800 mmmm[4748:188409] 任务4完成
//2019-04-12 00:34:00.028444+0800 mmmm[4748:188374] 全部搞完了


#pragma mark - 阻塞
/**
 https://www.jianshu.com/p/1f9f6814e3a2
 */
- (void)zusai {
    //在主线程写一段代码，并运行
      NSLog(@"1");
      dispatch_semaphore_t s = dispatch_semaphore_create(0);
      dispatch_async(dispatch_get_global_queue(0, 0), ^{
          dispatch_async(dispatch_get_main_queue(), ^{
              NSLog(@"2");
              dispatch_semaphore_signal(s);
          });
      });
      NSLog(@"3");
      dispatch_semaphore_wait(s, DISPATCH_TIME_FOREVER);
      NSLog(@"4");
}

- (void)zusai2 {
    //在主线程写一段代码，并运行
      NSLog(@"1");
      dispatch_semaphore_t s = dispatch_semaphore_create(0);
      dispatch_async(dispatch_get_global_queue(0, 0), ^{
          dispatch_semaphore_signal(s);
          dispatch_async(dispatch_get_main_queue(), ^{
              NSLog(@"2");
              
          });
      });
      NSLog(@"3");
      dispatch_semaphore_wait(s, DISPATCH_TIME_FOREVER);
      NSLog(@"4");
}

- (void)zusai3 {  //做到1234,实现不了
    //在主线程写一段代码，并运行
    NSLog(@"1");
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_enter(group);
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
      dispatch_async(dispatch_get_main_queue(), ^{
          NSLog(@"2");
          dispatch_async(dispatch_queue_create(0, 0), ^{
              dispatch_group_leave(group);
          });
      });
    });
    NSLog(@"3");
    dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
    NSLog(@"4");
}

#pragma mark -利用串形状队列做同步任务，但异步+并发开启了多条新线程，最里面的任务会在另一条队列里顺序执行
- (void)serialTest4 {
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    dispatch_queue_t queue = dispatch_queue_create("com.demo.serialQueue", DISPATCH_QUEUE_SERIAL);
    dispatch_async(queue, ^{
        for (int i = 0 ; i < 5; i++) {
            NSLog(@"开始%d",i);
            // 模拟请求 ↓
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                sleep(3);
                NSLog(@"任务%d完成",i);
//                dispatch_semaphore_signal(sema);
            });
            // 模拟请求 上
//           dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
        }
        
       NSLog(@"全部搞完了");
    });
}

#pragma mark --利用串形状队列做同步任务，同步+并发，最里面的任务会在全局队列里顺序执行
- (void)serialTest5 {
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    dispatch_queue_t queue = dispatch_queue_create("com.demo.serialQueue", DISPATCH_QUEUE_SERIAL);
    dispatch_async(queue, ^{
        for (int i = 0 ; i < 5; i++) {
            NSLog(@"开始%d",i);
            // 模拟请求 ↓
            dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                sleep(3);
                NSLog(@"任务%d完成",i);
//                dispatch_semaphore_signal(sema);
            });
            // 模拟请求 上
//           dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
        }
        
       NSLog(@"全部搞完了");
    });
}

@end
